package com.orchard.orchardfarmmanagementsystem.controller;

import com.orchard.orchardfarmmanagementsystem.entity.User;
import com.orchard.orchardfarmmanagementsystem.service.UserService;
import com.orchard.orchardfarmmanagementsystem.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/auth")
public class AuthController {

  @Autowired
  private UserService userService;

  @PostMapping("/login")
  public Result<Map<String, Object>> authenticateUser(@RequestBody LoginRequest loginRequest) {
    try {
      boolean authenticate = userService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());
      User user = userService.findByUsername(loginRequest.getUsername());

      if (!authenticate || user == null) {
        return Result.error(50001, "用户名或密码错误");
      }


      //颁发token
      String token = TokenUtil.generateToken(user.getUsername());



      // 构建响应数据
      Map<String, Object> userData = new HashMap<>();
      userData.put("name", user.getUsername()); // 假设User实体中有getName方法
      userData.put("avatar", user.getAvatarUrl()); // 实际应用中应该根据用户信息设置
      userData.put("token",token);


      // 返回成功的响应
      return Result.success("登录成功", userData);

    } catch (Exception e) {
      // 记录错误日志
      // logger.error("Error during login: ", e);
      return Result.error(50000, "网络故障");
    }
  }

  @GetMapping("/info")
  @PreAuthorize("hasAuthority('PERM_READ_DATA')")
  public Result<Map<String, Object>> getUserInfo(@RequestParam String token) {
    // 假设 TokenUtil.validateToken(token) 是一个静态方法，用于验证token的有效性
    if (!TokenUtil.validateToken(token)) {
      // 如果token验证失败，返回401状态码和错误信息
      return Result.error(401, "Invalid token, please login again.");
    }

    // 获取当前登录用户的信息，
    String username = TokenUtil.getUsernameFromToken(token);
    User user = userService.findByUsername(username);
    if (user == null) {
      // 如果没有找到用户信息，返回404状态码和错误信息
      return Result.error(404, "User not found.");
    }

    // 构建用户数据
    Map<String, Object> userData = new HashMap<>();
    userData.put("name", user.getUsername()); // 使用实际的getter方法
    userData.put("avatar", user.getAvatarUrl()); // 实际应用中应该根据用户信息设置

    // 返回包含用户数据的成功响应
    return Result.success(userData);
  }


  @PostMapping("/logout")
  @PreAuthorize("hasAuthority('PERM_READ_DATA')")
  public Result logout(@RequestHeader("Authorization") String authorizationHeader) {
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
      String token = authorizationHeader.substring(7);
      TokenUtil.expireToken(token); // 让Token立即失效
      return Result.success("退出登录成功");
    }
    return Result.error(50000,"网络故障");
  }
}